package com.ssb.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.ssb.service.check.CheckedFrontSysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 黄河接口对接-被保险人批改
 */
@Component
public class HheRiskRelateList extends HheSuperPlugin {

    @Autowired
    private CheckedFrontSysService checkedFrontSysService;

    @Override
    public Object beforeInvoke(Map<String, Object> map) {

        //校验此前端系统是否存在且有效
        String frontSysCode = StrUtil.doNull(String.valueOf(map.get("frontSysCode")));
        Map<String,String> result =  checkedFrontSysService.checkedSysByFrontSysCode(frontSysCode);
        if (result.get("errorCode").equals("F")){
            throw new BusinessException("此系统有误：" + result.get("errorMsg"));
        }

        String infoId=String.valueOf(map.get("infoId"));
        if(StrUtil.isNull(infoId)){
            throw new BusinessException("订单ID不能为空");
        }
        Object obj = getOrderById(infoId);
        if(!Validator.isEmpty(obj)){
            map.put("orderInfo",obj);
            customMethod(map);
        }
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        customMethod(map);
        return null;
    }

    private void customMethod(Map<String, Object> map){
        long startLong = System.currentTimeMillis();
        Map<String, Object> param = new HashMap<>();
        DataMap orderInfo = (DataMap)map.get("orderInfo");
        param.put("channel_id",StrUtil.doNull(String.valueOf(orderInfo.get("channelId")),"SSK"));//渠道编码，（默认：SSK）
        param.put("policyNo",orderInfo.get("policyNo"));//保单号
        param.put("requesttype","60");//交易类型（默认：60：批改）
        param.put("riskCode",map.get("riskCode"));//险种代码（家政险传值：1232）
        param.put("timestamp",System.currentTimeMillis());//时间戳（毫秒数）
        param.put("editType","U");//批改标志：（U:变更被保险人信息）
        param.put("endorType","01");//批改类型：01
        param.put("startDate",orderInfo.get("startDate"));//起保日期（YYYY-MM-DD HH:MM:SS）
        param.put("validDate",map.get("validDate"));//批改生效日期（YYYY-MM-DD）

        List<Map> mains = new ArrayList<>();
        Map mainMap = new HashMap<>();
        mainMap.put("groupInd",map.get("groupInd"));//是否为团单 1：否,2：是
        mains.add(mainMap);
        param.put("mainList",mains);//主节点

        List<Map> risks = new ArrayList<>();
        List<Map> list = (List)map.get("ssInsurPerson");
        if(!Validator.isEmpty(list)){
            for(int i=0;i<list.size();i++){
                Map insured = list.get(i);
                Map riskMap = new HashMap<>();
                riskMap.put("clientName",insured.get("insuredName"));//被保险人名称
                riskMap.put("identifyNo",insured.get("insuredCertiNo"));//证件号码
                riskMap.put("phone",insured.get("insuredPhone"));//电话
                riskMap.put("contactAdr",insured.get("insuredContactAdr"));//联系地址
                riskMap.put("originName",insured.get("originName"));//变更前被保险人名称
                riskMap.put("originIdentifyNo",insured.get("originIdentifyNo"));//变更前被保险人证件号码
                risks.add(riskMap);
            }
        }
        param.put("riskRelateList",risks);//变更被保险人信息

        String str = String.valueOf(sendInterface("Externalcommon/surrenderSSK", param,null));
        log.info("被保险人批改结果："+str);
        if(Validator.isNotNull(str)){//处理接口返回结果
            JSONObject json = JSON.parseObject(str);
            if("200".equals(json.getString("code"))){
                if(!Validator.isEmpty(list)) {
                    String sql = "update ss_insur_person set ";
                    String requestNo = String.valueOf(orderInfo.get("requestNo"));
                    for(int i=0;i<list.size();i++) {
                        Map insured = list.get(i);
                        StringBuilder sb = new StringBuilder(sql);
                        sb.append("insured_name='"+insured.get("insuredName")+"',");
                        sb.append("insured_certi_no='"+insured.get("insuredCertiNo")+"',");
                        sb.append("insured_phone='"+insured.get("insuredPhone")+"',");
                        sb.append("insured_contact_adr='"+insured.get("insuredContactAdr")+"'");
                        sb.append(" where request_no='"+requestNo+"'");
                        IusPluginUtil.getInstance().saveInvoke(DATA_SOURCE,sb.toString());
                    }
                }
            }
            map.put("resultData",json);
        }
        log.info("huanghe interface exetime = "+(System.currentTimeMillis()-startLong)+" ms");
    }
}
